package edu.whu.notepal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.whu.notepal.pojo.PrivateChat;
import edu.whu.notepal.service.ContactsService;
import edu.whu.notepal.service.NoteService;
import edu.whu.notepal.service.PrivateChatService;
import edu.whu.notepal.mapper.PrivateChatMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 陈磊
* @description 针对表【t_private_chat】的数据库操作Service实现
* @createDate 2022-12-02 20:27:25
*/
@Service
public class PrivateChatServiceImpl extends ServiceImpl<PrivateChatMapper, PrivateChat>
    implements PrivateChatService{

    @Resource
    NoteService noteService;

    @Resource
    ContactsService contactsService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createPrivateChat(Long noteId,Long visitorId) {
        noteService.changeVisible(noteId,Boolean.FALSE);
        PrivateChat privateChat = new PrivateChat();
        privateChat.setNoteId(noteId);
        privateChat.setStatus(0);
        privateChat.setPublisherId(noteService.getPublisher(noteId));
        privateChat.setVisitorId(visitorId);
        privateChat.setMessageCount(0);
        save(privateChat);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deletePrivateChat(Long noteId) {
        noteService.changeVisible(noteId,Boolean.TRUE);
        removeById(noteId);
    }

    @Override
    public List<PrivateChat> getChatById(Long id) {
        LambdaQueryWrapper<PrivateChat> privateChatWrapper = new LambdaQueryWrapper<>();
        privateChatWrapper.eq(PrivateChat::getPublisherId,id)
                .or().eq(PrivateChat::getVisitorId,id);
        return list(privateChatWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer makeFriends(Long noteId, Long userId) {
        PrivateChat privateChat = getById(noteId);
        Integer status = privateChat.getStatus();
        if(privateChat.getPublisherId().equals(userId)){
            status+=1;
        }
        else {
            status+=2;
        }
        privateChat.setStatus(status);
        updateById(privateChat);
        if(status==3){
            contactsService.saveBiDirection(privateChat.getPublisherId(),privateChat.getVisitorId());
        }
        return status;
    }

    @Override
    public Long getTheOther(Long noteId, Long fromUser) {
        PrivateChat privateChat = getById(noteId);
        if(fromUser.equals(privateChat.getPublisherId())){
            return privateChat.getVisitorId();
        }
        return privateChat.getPublisherId();
    }



}